<template>
  <a-button @click="router.back" type="outline" status="success">
    <icon-left />
    返回
  </a-button>
  <div style="margin-left: 240px" id="addUserView">
    <h2 style="margin-left: 620px">
      {{ updatePage ? "修改用户" : "创建用户" }}
    </h2>
    <a-form :model="form" label-align="right" :on-submit="doSubmit">
      <a-form-item field="id" label="学号: ">
        <a-input-number
          v-model="form.id"
          placeholder="请输入学号..."
          :style="{ width: '640px' }"
          :readonly="updatePage"
          :disabled="updatePage"
        />
      </a-form-item>
      <a-form-item field="username" label="用户名: ">
        <a-input
          v-model="form.username"
          placeholder="请输入用户名..."
          :style="{ width: '640px' }"
        />
      </a-form-item>
      <a-form-item field="clazz" label="班级: ">
        <a-input
          v-model="form.clazz"
          placeholder="请输入班级..."
          :style="{ width: '640px' }"
        />
      </a-form-item>
      <a-form-item field="score" label="分数: ">
        <a-input-number
          v-model="form.score"
          placeholder="请输入分数..."
          :style="{ width: '640px' }"
        />
      </a-form-item>
      <a-form-item field="acceptedQuestionIds" label="通过题目id集合:">
        <a-tooltip
          content="修改题目通过id后需要手动修改用户分数！"
          position="top"
        >
          <a-input-tag
            v-model="filteredAcceptedIds"
            :style="{ width: '640px' }"
            placeholder="请输入通过题目id..."
            allow-clear
          />
        </a-tooltip>
      </a-form-item>
      <a-form-item field="password" label="密码: ">
        <a-input
          v-model="form.password"
          placeholder="请输入修改后的密码..."
          :style="{ width: '640px' }"
        />
      </a-form-item>
      <a-form-item field="userRole" label="用户角色" style="min-width: 240px">
        <a-select
          v-model="form.userRole"
          placeholder="请选择用户角色"
          :style="{ width: '320px' }"
          allow-clear
        >
          <a-option value="user">user</a-option>
          <a-option value="admin">admin</a-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button
          @click="doSubmit"
          style="margin: 0 200px; min-width: 200px"
          type="primary"
          >提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  UserAddRequest,
  UserControllerService,
  UserUpdateRequest,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");
import { computed } from "vue";

// 在setup中定义计算属性
const filteredAcceptedIds = computed({
  get: () => form.value.acceptedQuestionIds?.filter((id) => id !== 0) ?? [],
  set: (newVal) => {
    form.value.acceptedQuestionIds = [
      0,
      ...(newVal?.filter((id) => id !== 0) || []),
    ];
  },
});

let form = ref<UserAddRequest>({
  id: undefined,
  username: undefined,
  password: undefined,
  clazz: undefined,
  score: 0,
  acceptedQuestionIds: [0],
  userRole: undefined,
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await UserControllerService.getUserById(id as never);
  if (res.code === 0) {
    // 精确匹配字段（假设后端返回结构为 { id: 123, ... }）
    form.value = {
      id: Number(res.data?.id) ?? undefined,
      username: res.data?.username ?? "",
      clazz: res.data?.clazz ?? undefined,
      score: res.data?.score ?? 0,
      acceptedQuestionIds:
        JSON.parse(res.data?.acceptedQuestionIds ?? "") ?? [],
      userRole: res.data?.userRole ?? undefined,
      password: undefined, // 密码通常不返回
    };
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  // 区分更新还是创建
  if (updatePage) {
    let updateRequest = ref<UserUpdateRequest>({
      id: undefined,
      username: undefined,
      password: undefined,
      acceptedQuestionIds: [],
      score: undefined,
      clazz: undefined,
      userRole: undefined,
    });
    updateRequest.value.id = form.value.id;
    updateRequest.value.username = form.value.username;
    updateRequest.value.password = form.value.password;
    updateRequest.value.acceptedQuestionIds = form.value.acceptedQuestionIds;
    updateRequest.value.score = form.value.score;
    updateRequest.value.clazz = form.value.clazz;
    updateRequest.value.userRole = form.value.userRole;
    const res = await UserControllerService.updateUser(updateRequest.value);
    if (res.code === 0) {
      message.success("更新成功");
      await router.push({
        path: "/manage/user",
        replace: true,
      });
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    const res = await UserControllerService.addUser(form.value);
    if (res.code === 0) {
      message.success("创建成功");
      await router.push({
        path: "/manage/user",
        replace: true,
      });
    } else {
      message.error("创建失败，" + res.message);
    }
  }
};
</script>

<style scoped></style>
